package com.zhouqinuan.spring.cloud.develop.framework.redis.util;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;

public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void set(String key, Object object, int expireTime, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, object, expireTime, timeUnit);
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key) {

        return (T) redisTemplate.opsForValue().get(key);
    }

    /**
     * 设置锁
     * 
     * @param key
     *            锁的键
     * @param value
     *            锁的值
     * @param timeout
     *            锁超时时间，单位:秒
     * 
     */
    public boolean setLockValue(final String key, final String value, final int timeout) {
        if (StringUtils.isNotEmpty(key)) {
            try {
                Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, value);
                if (flag) {
                    redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
                    return true;
                }
            } catch (Exception e) {
                return false;
            }
        }

        return false;
    }

    /**
     * 设置锁并等待
     * 
     * @param key
     *            锁的键
     * @param value
     *            锁的值
     * @param timeout
     *            锁超时时间，单位:秒
     * @param wait
     *            等待锁的时间，单位：秒
     * 
     */
    public boolean setLockValueAndWait(final String key, final String value, final int timeout, final int wait) {
        if (StringUtils.isNotEmpty(key)) {
            try {
                int cnt = 0;
                do {
                    Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, value);
                    if (flag) {
                        redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
                        return true;
                    } else {
                        cnt += 50;
                        Thread.sleep(50);
                    }
                } while (cnt <= wait * 1000);
            } catch (Exception e) {
                return false;
            }
        }

        return false;
    }

    @SuppressWarnings("unchecked")
    public void delete(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }
}
